library(ggplot2)

set.seed(123)
# a
tripleshift <- c(-1, 1, 3)
# 三个数据集的三个中心mean shift
classlabel <- c("c1", "c2", "c3")
cols <- 50
rows <- 20

simulate1 <- data.frame(matrix(round(rnorm(rows * cols, mean = tripleshift[1]), 3),
                    nrow = rows), name = classlabel[1])
simulate2 <- data.frame(matrix(round(rnorm(rows * cols, mean = tripleshift[2]), 3),
                    nrow = rows), name = classlabel[2])
simulate3 <- data.frame(matrix(round(rnorm(rows * cols, mean = tripleshift[3]), 3),
                    nrow = rows), name = classlabel[3])
combinedataset <- data.frame(rbind(simulate1, simulate2, simulate3))
dim(combinedataset)
# combinedataset
colnames(combinedataset) <- paste("var", seq_len(ncol(combinedataset)))
rownames(combinedataset) <- paste("obs", seq_len(nrow(combinedataset)))
# b
dataset1 <- combinedataset[1: 50]
pcadataset <- prcomp(dataset1, scale = T)
summary(pcadataset)
combinedataset[51]
datasetname <- factor(unlist(combinedataset[51]))
# 列表格式无法直接用factor()转换，需要先用unlist()转化为向量
# datasetname
colorset <- c("red", "yellow", "green")
par(mar = c(4, 4, 1, 1))
biplot(pcadataset, scale=0)
ggplot(pcadataset$x, aes(x=PC1, y=PC2, color = colorset[datasetname])) + geom_point()
# 颜色取集合名的转换因子
# c
result1 <- kmeans(dataset1, 3, iter.max = 50, algorithm = "Lloyd")
clustercolor <- factor(result1$cluster)
ggplot(pcadataset$x, aes(x=PC1, y=PC2, color = clustercolor)) + geom_point()
table(result1$cluster)
# d
result2 <- kmeans(dataset1, 2, iter.max = 50, algorithm = "Lloyd")
clustercolor2 <- factor(result2$cluster)
ggplot(pcadataset$x, aes(x=PC1, y=PC2, color = clustercolor2)) + geom_point()
table(result2$cluster)
# e
result3 <- kmeans(dataset1, 4, iter.max = 50, algorithm = "Lloyd")
clustercolor3 <- factor(result3$cluster)
ggplot(pcadataset$x, aes(x=PC1, y=PC2, color = clustercolor3)) + geom_point()
table(result3$cluster)
# f
result4 <- kmeans(pcadataset$x, 3, iter.max = 50, algorithm = "Lloyd")
clustercolor4 <- factor(result4$cluster)
ggplot(pcadataset$x, aes(x=PC1, y=PC2, color = clustercolor4)) + geom_point()
table(result4$cluster)
# g
scaledataset <- scale(combinedataset[1: 50], scale = T)
result5 <- kmeans(scaledataset, 3, iter.max = 50, algorithm = "Lloyd")
clustercolor5 <- factor(result5$cluster)
ggplot(pcadataset$x, aes(x=PC1, y=PC2, color = clustercolor5)) + geom_point()
table(result5$cluster)